<template>
  <div class="container">
    <div class="sidebar">
      <!-- <el-tree node-key="id" :data="phrldata" :props="dPs"  @node-click="handleNodeClick" default-expand-all :highlight-current="highlightBd" ref="treeRef" :current-node-key='currentKey'></el-tree> -->
      <el-dropdown  @command="handleCommand">
        <el-button style="margin-top: 10px; margin-left:10px">
          传感器<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown"  type="primary" >
          <el-dropdown-item v-for="item in deviceList" :key="item.value" :command="item">{{ item.name }}</el-dropdown-item>
          <!-- <el-dropdown-item>狮子头</el-dropdown-item>
          <el-dropdown-item>螺蛳粉</el-dropdown-item>
          <el-dropdown-item disabled>双皮奶</el-dropdown-item>
          <el-dropdown-item divided>蚵仔煎</el-dropdown-item> -->
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <div class="content">
      <!-- activeName -->
      <el-tabs v-model="activeName"  @tab-click="handleClick">
        <!-- <el-button @click="getList"> get</el-button> -->
      
        <el-tab-pane :label="`浸润数据图 ${choseDeviceName}`" name="first">
          <div class="chart-container">
            <!-- <chart v-loading="loading" height="100%" width="100%" :chartData="chartData" :chartRiqi="chartRiqi" /> -->
            <chart  height="100%" width="100%" :chartData="chartData" :chartRiqi="chartRiqi" />
          </div>
        </el-tab-pane>
        <!-- <el-tab-pane label="降雨速率图" name="second"></el-tab-pane> -->
        <!-- <el-tab-pane label="刨面内侧点缩略图" name="third"></el-tab-pane> -->
      </el-tabs>
    </div>
    
    
  </div>
</template>

<script>
import chart from '../../components/charts/Mix-phrl.vue'
import { getDevicePhrlData, listDevice, listNewDevice, sensorPointList  } from "@/api/screen/device";

export default {
  name: 'graph',
  components: { chart },
  data() {
    return {
      choseDeviceName: '',
      currentKey: 0,
      activeName: 'first',
      chartRiqi: [
        // '2023-11-11', '2023-11-12', '2023-11-13', '2023-11-14', '2023-11-15', '2023-11-16', '2023-11-17'
      ],
      devicePhrlDataList: [],
      highlightBd: true,
      phrldata: [],
     
          
        activeName: 'first',
        chartData: [
          // 150, 230, 224, 218, 135, 147, 280
        ],
        chartRiqi: [
          // '2023-11-11', '2023-11-12', '2023-11-13', '2023-11-14', '2023-11-15', '2023-11-16', '2023-11-17'
        ],
        deviceList: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        elTreeData: [],
        loading: true,
      }
  },
  computed: {
    dPs() {
      return {
        children: 'children',
        label: 'label'
      };
    }
  },
  mounted() {
    // this.getList()
  //   .then(() => {
  //   getList已完成，现在可以安全地假定树形控件数据已经准备好
  //   console.log("Tree data should now be ready.");
  // });
  this.username = this.$store.state.user.name
    if(this.username == 'maguan') {
        this.getsensorPoint('马关')
      }
      else if (this.username == 'guanxi'){
        this.getsensorPoint('关西')
      }
      else {
        this.getsensorPoint()
      }
    
  },
  methods: {
    // 选择传感器
    handleCommand(command) {
        console.log('command', command)
        this.choseDeviceName = command.name
        listNewDevice({strPointId: command.strId,pageSize:500, isAsc: 'desc',orderByColumn: 'time'}).then(response => {
        console.log('deviceLevelDataList',response.rows) 
        this.loading = false
        // let resList = response.rows
        // this.deviceLevelDataList = resList.reverse()
        this.loading = false
        this.deviceLevelDataList = response.rows
        this.chartRiqi = this.deviceLevelDataList.map(item=> {return item.createTime})
        this.chartData = this.deviceLevelDataList.map(item=> {return ((item.resultData.substr(0, item.resultData.length-1)).split(':'))[1] })
        console.log('this.chartData-phrl', this.chartData)
        console.log('this.chartData-phrl', this.chartRiqi)
        }
      );
      },
     //站点列表
     getsensorPoint(e) {
        sensorPointList({name: e, sensorName: '测缝', pageSize: 100}).then(response=> {
          this.deviceList = response.rows
          console.log('deviceListPhrl',this.deviceList ) 
          // this.convertToElTree()
          this.groupByDeviceId()
          // 选择并处理第一个树节点
          // if (this.deviceList?.length > 0 && this.deviceList[0].children && this.deviceList[0].children?.length > 0) {
          //   const firstNodeId = this.deviceList[0].children[0].id;
          //   this.handleNodeClick({id: firstNodeId});
          // }

          console.log('this.deviceList', this.deviceList)
          // monitordevicecode 所属监测点
          // monitordevicename 设备类型
          // deviceid  设备id
          this.total = response.total;
          this.loading = false;

        })
      },
      handleClick (tab, event) {
      console.log(tab, event)
    },
    handleClick (tab, event) {
      console.log(tab, event)
    },
     /** 查询设备列表 */
    getList() {
      this.loading = true;
      listNewDevice({resultData:'phrlData', pageSize:20}).then(response => {
        console.log('deviceListPhrl',response.rows) 
        this.deviceList = response.rows
        this.groupByDeviceId()

         // 选择并处理第一个树节点
        if (this.phrldata.length > 0 && this.phrldata[0].children && this.phrldata[0].children.length > 0) {
        const firstNodeId = this.phrldata[0].children[0].id;
        this.handleNodeClick({id: firstNodeId});
         }
        // this.convertToElTree()
        console.log('this.deviceList', this.deviceList)
        // monitordevicecode 所属监测点
        // monitordevicename 设备类型
        // deviceid  设备id
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
    console.error("Error fetching device list:", error);
    this.loading = false;
        }
      );
    },
    // 函数根据 deviceId 对设备进行分组
    groupByDeviceId(devices = this.deviceList) {
        return devices.reduce((groups, device) => {
          const { deviceId } = device;
          if (!groups[deviceId]) {
            groups[deviceId] = [];
          }
          groups[deviceId].push({
            label: device.deviceName,
            ...device
          });
          console.log('groups', groups)
          this.groupedDevices = groups


          // 将分组转换为 el-tree 的数据格式（每个分组一个树）
          this.phrldata = Object.keys(this.groupedDevices).map(deviceId => {
            return {
              label: `位置编号 ${deviceId}`,
              children: this.groupedDevices[deviceId]
              // children: this.groupedDevices[{ id: device.deviceId, label: device.deviceName  }]
            };
          });
          return groups;
        }, {});
      },
    /** 查询降雨量设备数据详情 */
    getDevicePhrlData(e) {
      this.loading = true;
      getDevicePhrlData({deviceId:e, isAsc:'desc', orderByColumn:'createTime'}).then(response => {
        console.log('devicePhrlDataList',response.rows) 
        this.loading = false
        // let resList = response.rows
        // this.devicePhrlDataList = resList.reverse()
        this.devicePhrlDataList = response.rows
        this.chartRiqi = this.devicePhrlDataList.map(item=> {return item.createTime})
        this.chartData = this.devicePhrlDataList.map(item=> {return item.tag})
        console.log('this.chartData', this.chartData, this.chartRiqi)
        }
      );
    },
    handleNodeClick(phrldata) {
      console.log(phrldata, phrldata.id);
      if( phrldata.id == null) {
        console.log('null')
      } else {
        this.getDevicePhrlData(phrldata.deviceId)
        this.currentKey = phrldata.deviceId
        this.$nextTick(() => {
          this.$refs['treeRef'].setCurrentKey(this.currentKey)
        })
      }
    },
    convertToElTree(e = this.deviceList) {
        const tempMap = new Map(); // 临时 Map 用于合并相同项
        // 遍历设备列表
        e.forEach(device => {
          if (tempMap.has(device.projectName) || tempMap.has(device.monitorDeviceName)) {
             // 如果存在相同设备名称的项，则合并
             const existingDevice = tempMap.get(device.projectName);
            //  const existingMonitordevicename = tempMap.get(device.monitordevicename);
             existingDevice.children.push({ id: device.deviceId, label: device.deviceName });
          } else {
             // 如果不存在相同设备名称的项，则创建新节点
             tempMap.set(device.projectName, {
              label: device.projectName,
              children: [{ id: device.deviceId, label: device.deviceName  }]
            });
            // 如果不存在相同设备名称的项，则创建新节点
            
          }
        });
        
        // 将 Map 转换为数组，存储到 elTreeData 中
        this.elTreeData = Array.from(tempMap.values());

        this.phrldata = this.elTreeData
        console.log('this.elTreeData', this.elTreeData)
      }
  }
}
</script>

<style scoped>
.el-tree-node:focus > .el-tree-node__content {
  color:  #409eff;
  /* transition: background 1s; */
}

.container {
  display: flex;
}

  
.sidebar {
  width: 200px; /* Adjust the width as per your layout */
  height: 100vh;
}

.content {
  flex: 1;
  height: 100vh;
}


.chart-container{
position: relative;
width: 100%;
height: 80vh;
}


</style>